<?php

// No direct access to this file
defined('_JEXEC') or die('Restricted access');	
JTable::addIncludePath(JPATH_COMPONENT.DIRECTORY_SEPARATOR.'tables');
class BakerysModelBilladdress extends JModelItem
{
	public function getTable($type = 'Billaddress', $prefix = 'BakerysTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}
	
	public function getUserInfo($userid)
	{
		$db		= $this->getDbo();
		$query	= $db->getQuery(true);
		$query->select("*");
		$query->from("#__bakery_orders");
		$query->where("user_id = $userid");
		$query->order("create_date DESC");
		$db->setQuery($query,0,1);
		return $db->loadObject();	
	}
	
	public function createorder()
	{	
		$session = JFactory::getSession();
		$post = JRequest::get("post");
		$location_id = JRequest::getVar("location_id");
		$location_alias = JRequest::getVar("location_alias");
		$cart = $session->get("bakery_cart_".$location_id);
		
		if(!isset($cart)) 
		{
			$app = JFactory::getApplication();
			$link = JRoute::_("index.php?option=com_bakerys&view=bakerys&location=".$location_id.":".$location_alias);
			$app->redirect($link);
		}
		
		$create_date = date('Y-m-d H:i:s');	
		$order_date = date('Y-m-d H:i:s');
		
		$post["create_date"] = $create_date;
		$post["order_date"] = $order_date;
		$user = JFactory::getUser();
		if($user->guest)
		{
			$post["email"] = $session->get("guest_mail");
			$post["user_id"] = 0;
		}else 
		{
			$post["email"] = "";
			$post["user_id"] = $user->id;
		}
		
		$table = $this->getTable();
		$table->bind($post);
		$table->store();
		$order_id = $table->id;
		
		$total_amount=0;	
		$db = JFactory::getDbo();
		$query = "insert into #__bakery_orderdetail(order_id,item_id,quantity,price,amount) values";
		$insert = array();
		foreach($cart as $cart_item)
		{
			$item_id = $cart_item["productid"];
			$price = $cart_item["price"];
			$quantity = $cart_item["quantity"];
			$amount = $price * $quantity;
			$total_amount += $amount;
			$insert[] = "($order_id,$item_id,$quantity,$price,$amount)";
		}
		
		if(count($insert) > 0)
		{
			$query .= implode(",", $insert);
			$db->setQuery($query);
			$db->query();
			
			$query = "update #__bakery_orders set total_amount = $total_amount where id = $order_id";
			$db->setQuery($query);
			$db->query();
			
		}
		$session->clear("bakery_cart_".$location_id);
		return true;	
	}
	
}
